<?php
/**
 * CompleXml Framework
 *
 * @category   CompleXml
 * @package    CompleXml_Object
 * @copyright  Copyright (c) 2008 Andrey Kucherenko
 * @license    New BSD License
 * @version    $Id: Router.php 8 2008-11-13 14:50:42Z kucherenko.andrey $
 */
require_once 'CompleXml/Object/Abstract.php';
require_once 'CompleXml/Dataset/Request.php';
class CompleXml_Object_Router extends CompleXml_Object_Abstract
{
	/**
	 * CompleXml_Dataset_Request object
	 * @var CompleXml_Dataset_Request
	 */
	public $Request;

	private $_controllers_path = null;

	public function __construct ()
	{
		$this->Request = new CompleXml_Dataset_Request();
	}

	public function setControllersPath($path)
	{
		$this->_controllers_path = $path;
	}

	public function setHandlers($handlers)
	{
		CompleXml_Config::set('complexml_handlers', $handlers);
	}

	public function setActions($actions)
	{
		CompleXml_Config::set('complexml_actions', $actions);
	}

	public function setLocale($locale)
	{
		CompleXml_Config::set('complexml_locale', $locale);
		
	}
	public function setTemplate($template)
	{
		CompleXml_Config::set('complexml_template', $template);
	}

	static protected function canBrowserXsltProccess($browser)
	{
		$info = get_browser($browser);
		$version = (float) $info->version;
		switch ($info->browser) {
			case 'Opera':
				if ($version>=9.0){
					return true;
				}
				break;
			case 'IE':
				if ($version>=6.0){
					return true;
				}
				break;
			case 'Firefox':
				if ($version>=2.0){
					return true;
				}
				break;
			default:
				return false;
				break;
		}
	}

	public function setNeedleOutputHandler()
	{
		if (isset($_SERVER[ 'HTTP_X_REQUESTED_WITH' ]) || $this->Request->getBool('xml')){
			require_once 'CompleXml/Handler/Output/Xml.php';
			$xmlOutputHandler = new CompleXml_Handler_Output_Xml();
			$handlers = array($xmlOutputHandler);
		}elseif (self::canBrowserXsltProccess(getenv('HTTP_USER_AGENT'))){
			require_once 'CompleXml/Handler/Output/Browser.php';
			$browserOutputHandler = new CompleXml_Handler_Output_Browser();
			$handlers = array($browserOutputHandler);
		}else{
			require_once 'CompleXml/Handler/Output/Xslt.php';
			$xslOutputHandler = new CompleXml_Handler_Output_Xslt();
			$handlers = array($xslOutputHandler);
		}
		CompleXml_Config::set('complexml_handlers', $handlers);
	}

	protected function start($page)
	{
		if (!file_exists($this->_controllers_path.DIRECTORY_SEPARATOR.$page.'.php')){
			require_once 'CompleXml/Object/Router/Exception.php';
			throw new CompleXml_Object_Router_Exception('Controller "'.$this->_controllers_path.DIRECTORY_SEPARATOR.$page.'.php" not exists');
		}
		require_once($this->_controllers_path.DIRECTORY_SEPARATOR.$page.'.php');
		CompleXml_Core::start(new $page);
	}
}